package com.xxyy.mylive.ui.fragment;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.xxyy.mylive.R;
import com.xxyy.mylive.adapter.HomeListAdapter;
import com.xxyy.mylive.http.HttpApi;
import com.xxyy.mylive.tools.UiTool;
import com.xxyy.mylive.ui.BaseFragment;
import com.xxyy.mylive.ui.activity.CommonVideoActivity;
import com.xxyy.mylive.ui.activity.LiveVideoActivity;
import com.xxyy.mylive.ui.activity.RecordingActivity;
import com.xxyy.mylive.ui.activity.VrVideoActivity;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 首页
 */
public class HomeFragment extends BaseFragment implements View.OnClickListener {
    private RecyclerView recyclerView;
    private HomeListAdapter adapter;

    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public View getView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        recyclerView = (RecyclerView) view.findViewById(R.id.home_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        return view;
    }

    @Override
    protected void initData() {
        List<String> list = new ArrayList();
        list.add("fefef");
        list.add("efef");
        list.add("efef");
        list.add("efef");
        list.add("efef");
        adapter = new HomeListAdapter(getActivity(), list);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                if (parent.getChildPosition(view) != 0) {
                    outRect.top = 20;
                }
            }
        });
    }

    @Override
    protected void setListener() {
        adapter.setOnItemClickListener(new HomeListAdapter.OnItemClickListener() {
            @Override
            public void onItemclick(View view, int viewType) {
                Class<?> cls = null;
                String playUrl = "";
                switch (viewType) {
                    case 1001:
                        //普通视频
                        cls = CommonVideoActivity.class;
                        playUrl = "http://v.1318.com/jcs_opening/160324220108031416.flv";
                        break;
                    case 1002:
                        //VR视频
                        cls = VrVideoActivity.class;
                        playUrl = "http://v.1318.com/jcs_opening/160324220108031416.flv";
                        break;
                    case 1003:
                        //直播
                        cls = LiveVideoActivity.class;
                        playUrl = HttpApi.RTMP_PLAY_HOST;
                        break;
                }
                //进入观看直播页或视频页
                Intent intent = new Intent(getActivity(), cls);
                intent.putExtra("play_stream", playUrl);
                startActivity(intent);
            }
        });
    }

    /**
     * 获取推流地址
     *
     * @return
     */
    private String requestStreamJson() {
        try {
            // Replace "Your app server" by your app sever url which can get the StreamJson as the SDK's input.
            HttpURLConnection httpConn = (HttpURLConnection) new URL(HttpApi.RTMP_PUBLISH_HOST).openConnection();
            httpConn.setConnectTimeout(5000);
            httpConn.setReadTimeout(10000);
            int responseCode = httpConn.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                return null;
            }

            int length = httpConn.getContentLength();
            if (length <= 0) {
                return null;
            }
            InputStream is = httpConn.getInputStream();
            byte[] data = new byte[length];
            int read = is.read(data);
            is.close();
            if (read <= 0) {
                return null;
            }
            return new String(data, 0, read);
        } catch (Exception e) {
            UiTool.showToast(getActivity(), "Network error!");
        }
        return null;
    }

    private void startLive() {
        //获取rtmp直播地址，然后开始直播
        String streamJson = HttpApi.RTMP_PUBLISH_HOST;
        Intent intent = new Intent(getActivity(), RecordingActivity.class);
        intent.putExtra("publish_rtmp", streamJson);
        startActivity(intent);

//        String streamJson = requestStreamJson();
//        if (null != streamJson) {
//            Intent intent = new Intent(HomeActivity.this, RecordingActivity.class);
//            intent.putExtra("publish_stream_json", streamJson);
//            startActivity(intent);
//        } else {
//            UiTool.showToast(this, "获取直播地址失败");
//        }
    }


    @Override
    public void onClick(View view) {
//        switch (view.getId()) {
//            case R.id.btn_startLive:
//                if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) !=
//                        PackageManager.PERMISSION_GRANTED) {
//                    //申请直播需要的危险权限
//                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA
//                            , Manifest.permission.WRITE_EXTERNAL_STORAGE
//                            , Manifest.permission.RECORD_AUDIO}, 10);
//                } else {
//                    //已经授权，开始直播
//                    startLive();
//                }
//                break;
//        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 10) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //授权相机成功
                startLive();
            } else {
                //拒绝授权
                UiTool.showToast(getActivity(), "无法开启直播，请允许相关权限");
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
